Skip to content

Metric metric

Bases: SynalinksSaveable

Per-sample metric base; subclass it, or BatchMetric if it needs the batch.

During fit() / evaluate(), an update_state() that also declares an x argument receives the program's inputs (per sample, or the batch's list for a BatchMetric), e.g. to grade with a judge that needs the question.

Example:

program.compile(
    metrics=[
        synalinks.metrics.Metric(),
    ],
)

Parameters:

Name Type Description Default
name str

(Optional) string name of the metric instance.

None
in_mask list

(Optional) list of keys to keep to compute the metric.

None
out_mask list

(Optional) list of keys to remove to compute the metric.

None
in_mask_pattern str

(Optional) Regex pattern; fields whose names match are kept (combined with in_mask via OR).

None
out_mask_pattern str

(Optional) Regex pattern; fields whose names match are dropped (combined with out_mask via OR).

None

Attributes:

Name Type Description
direction str | None

Class-level optimization direction. "up" if higher values are better (accuracy, F1, reward), "down" if lower is better (cost, latency, token usage, errors). Defaults to "up"; operational (LM, embedding model, program) metrics default to "down". Consumers (EarlyStopping, ProgramCheckpoint, Keras-Tuner inference) use it to resolve mode="auto". Setting it to None forces an explicit mode= / direction=.

Source code in synalinks/src/metrics/metric.py
@synalinks_export(["synalinks.Metric", "synalinks.metrics.Metric"])
class Metric(SynalinksSaveable):
    """Per-sample metric base; subclass it, or BatchMetric if it needs the batch.

    During `fit()` / `evaluate()`, an `update_state()` that also declares an `x`
    argument receives the program's inputs (per sample, or the batch's list for
    a `BatchMetric`), e.g. to grade with a judge that needs the question.

    Example:

    ```python
    program.compile(
        metrics=[
            synalinks.metrics.Metric(),
        ],
    )
    ```

    Args:
        name (str): (Optional) string name of the metric instance.
        in_mask (list): (Optional) list of keys to keep to compute the metric.
        out_mask (list): (Optional) list of keys to remove to compute the metric.
        in_mask_pattern (str): (Optional) Regex pattern; fields whose names match
            are kept (combined with ``in_mask`` via OR).
        out_mask_pattern (str): (Optional) Regex pattern; fields whose names match
            are dropped (combined with ``out_mask`` via OR).

    Attributes:
        direction (str | None): Class-level optimization direction. ``"up"`` if
            higher values are better (accuracy, F1, reward), ``"down"`` if
            lower is better (cost, latency, token usage, errors). Defaults to
            ``"up"``; operational (LM, embedding model, program) metrics
            default to ``"down"``. Consumers (EarlyStopping, ProgramCheckpoint,
            Keras-Tuner inference) use it to resolve ``mode="auto"``. Setting
            it to ``None`` forces an explicit `mode=` / `direction=`.
    """

    direction = "up"

    def __init__(
        self,
        name=None,
        description=None,
        in_mask=None,
        out_mask=None,
        in_mask_pattern=None,
        out_mask_pattern=None,
    ):
        self.name = name or auto_name(self.__class__.__name__)
        self.description = docstring_summary(self) if description is None else description
        self._metrics = []
        self._variables = []
        self.in_mask = in_mask
        self.out_mask = out_mask
        self.in_mask_pattern = in_mask_pattern
        self.out_mask_pattern = out_mask_pattern
        self._tracker = Tracker(
            {
                "variables": (
                    lambda x: isinstance(x, backend.Variable),
                    self._variables,
                ),
                "metrics": (lambda x: isinstance(x, Metric), self._metrics),
            }
        )

    async def close(self):
        """Release what this metric holds. Idempotent.

        Nothing, for most metrics; a judge's program, for one wrapping a judge.
        """

    def reset_state(self):
        """Reset all of the metric state variables.

        This function is called between epochs/steps,
        when a metric is evaluated during training.
        """
        for v in self.variables:
            initializer = initializers.Empty(data_model=v._data_model)
            v.assign(initializer.get_json())

    async def update_state(self, *args, **kwargs):
        """Accumulate statistics for the metric."""
        raise NotImplementedError

    def result(self):
        """Compute the current metric value.

        Returns:
            (float | dict): A scalar, or a dictionary of scalars.
        """
        raise NotImplementedError

    def add_variable(self, initializer=None, data_model=None, name=None):
        if initializer is None:
            initializer = initializers.Empty(data_model=data_model)
        self._check_super_called()
        with backend.name_scope(self.name.replace("/", ">"), caller=self):
            initializer = initializer
            variable = backend.Variable(
                initializer=initializer,
                data_model=data_model,
                trainable=False,
                name=name,
            )
        # Prevent double-tracking
        self._tracker.add_to_store("variables", variable)
        return variable

    @property
    def variables(self):
        variables = list(self._variables)
        for metric in self._metrics:
            variables.extend(metric.variables)
        return variables

    async def __call__(self, *args, **kwargs):
        self._check_super_called()
        await self.update_state(*args, **kwargs)
        return self.result()

    def get_config(self):
        """Return the serializable config of the metric.

        Returns:
            (dict): The config dict.
        """
        return {
            "in_mask": self.in_mask,
            "out_mask": self.out_mask,
            "in_mask_pattern": self.in_mask_pattern,
            "out_mask_pattern": self.out_mask_pattern,
            "name": self.name,
            "description": self.description,
        }

    @classmethod
    def from_config(cls, config):
        """Returns a metric instance from config.

        Args:
            config (dict): The config dict.

        Returns:
            (Metric): The metric instance.
        """
        return cls(**config)

    def __setattr__(self, name, value):
        # Track Variables, Layers, Metrics
        if hasattr(self, "_tracker"):
            value = self._tracker.track(value)
        return super().__setattr__(name, value)

    def _check_super_called(self):
        if not hasattr(self, "_tracker"):
            raise RuntimeError(
                "You forgot to call `super().__init__()` "
                "in the `__init__()` method. Go add it!"
            )

    def __repr__(self):
        return f"<{self.__class__.__name__} name={self.name}>"

    def __str__(self):
        return self.__repr__()

close() async

Release what this metric holds. Idempotent.

Nothing, for most metrics; a judge's program, for one wrapping a judge.

Source code in synalinks/src/metrics/metric.py
async def close(self):
    """Release what this metric holds. Idempotent.

    Nothing, for most metrics; a judge's program, for one wrapping a judge.
    """

from_config(config) classmethod

Returns a metric instance from config.

Parameters:

Name Type Description Default
config dict

The config dict.

required

Returns:

Type Description
Metric

The metric instance.

Source code in synalinks/src/metrics/metric.py
@classmethod
def from_config(cls, config):
    """Returns a metric instance from config.

    Args:
        config (dict): The config dict.

    Returns:
        (Metric): The metric instance.
    """
    return cls(**config)

get_config()

Return the serializable config of the metric.

Returns:

Type Description
dict

The config dict.

Source code in synalinks/src/metrics/metric.py
def get_config(self):
    """Return the serializable config of the metric.

    Returns:
        (dict): The config dict.
    """
    return {
        "in_mask": self.in_mask,
        "out_mask": self.out_mask,
        "in_mask_pattern": self.in_mask_pattern,
        "out_mask_pattern": self.out_mask_pattern,
        "name": self.name,
        "description": self.description,
    }

reset_state()

Reset all of the metric state variables.

This function is called between epochs/steps, when a metric is evaluated during training.

Source code in synalinks/src/metrics/metric.py
def reset_state(self):
    """Reset all of the metric state variables.

    This function is called between epochs/steps,
    when a metric is evaluated during training.
    """
    for v in self.variables:
        initializer = initializers.Empty(data_model=v._data_model)
        v.assign(initializer.get_json())

result()

Compute the current metric value.

Returns:

Type Description
float | dict

A scalar, or a dictionary of scalars.

Source code in synalinks/src/metrics/metric.py
def result(self):
    """Compute the current metric value.

    Returns:
        (float | dict): A scalar, or a dictionary of scalars.
    """
    raise NotImplementedError

update_state(*args, **kwargs) async

Accumulate statistics for the metric.

Source code in synalinks/src/metrics/metric.py
async def update_state(self, *args, **kwargs):
    """Accumulate statistics for the metric."""
    raise NotImplementedError